package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.CommissionRecord;
import com.zhentao.pojo.User;
import com.zhentao.mapper.CommissionRecordMapper;
import com.zhentao.mapper.UserMapper;
import com.zhentao.service.CommissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 佣金服务实现类
 */
@Slf4j
@Service
public class CommissionServiceImpl implements CommissionService {

    @Resource
    private CommissionRecordMapper commissionRecordMapper;

    @Resource
    private UserMapper userMapper;

    // 提成比例配置（实际项目中应该从数据库或配置中心读取）
    private static final Map<String, BigDecimal> COMMISSION_RATIOS = new HashMap<>();

    static {
        // 普通用户提成比例
        COMMISSION_RATIOS.put("普通用户_普通会员", new BigDecimal("0.05")); // 5%
        COMMISSION_RATIOS.put("普通用户_高级会员", new BigDecimal("0.08")); // 8%
        COMMISSION_RATIOS.put("普通用户_VIP会员", new BigDecimal("0.10")); // 10%

        // 红娘提成比例
        COMMISSION_RATIOS.put("红娘_普通会员", new BigDecimal("0.08")); // 8%
        COMMISSION_RATIOS.put("红娘_高级会员", new BigDecimal("0.12")); // 12%
        COMMISSION_RATIOS.put("红娘_VIP会员", new BigDecimal("0.15")); // 15%

        // 各段位会员提成比例
        COMMISSION_RATIOS.put("会员_普通会员", new BigDecimal("0.10")); // 10%
        COMMISSION_RATIOS.put("会员_高级会员", new BigDecimal("0.15")); // 15%
        COMMISSION_RATIOS.put("会员_VIP会员", new BigDecimal("0.20")); // 20%
    }

    @Override
    public CommissionRecord calculateCommission(String parentUserId, String childUserId, BigDecimal amount, String memberType) {
        try {
            // 获取上级用户信息
            User parentUser = userMapper.selectById(parentUserId);
            if (parentUser == null) {
                throw new RuntimeException("上级用户不存在");
            }

            // 获取下级用户信息
            User childUser = userMapper.selectById(childUserId);
            if (childUser == null) {
                throw new RuntimeException("下级用户不存在");
            }

            // 确定用户类型
            String userType = getUserType(parentUser);

            // 获取提成比例
            BigDecimal ratio = getCommissionRatio(userType, memberType);

            // 计算提成金额
            BigDecimal commissionAmount = amount.multiply(ratio);

            // 创建佣金记录
            CommissionRecord record = new CommissionRecord();
            record.setParentUserId(parentUserId);
            record.setChildUserId(childUserId);
            record.setAmount(amount);
            record.setCommissionAmount(commissionAmount);
            record.setRatio(ratio);
            record.setMemberType(memberType);
            record.setUserType(userType);
            record.setStatus(1);
            record.setCreateTime(LocalDateTime.now());

            return record;
        } catch (Exception e) {
            log.error("计算提成失败: parentUserId={}, childUserId={}, amount={}, memberType={}",
                    parentUserId, childUserId, amount, memberType, e);
            throw new RuntimeException("计算提成失败: " + e.getMessage());
        }
    }

    @Override
    public boolean recordCommission(CommissionRecord record) {
        try {
            int result = commissionRecordMapper.insert(record);
            return result > 0;
        } catch (Exception e) {
            log.error("记录提成失败", e);
            return false;
        }
    }

    @Override
    public List<CommissionRecord> getCommissionRecords(String userId) {
        try {
            QueryWrapper<CommissionRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_user_id", userId)
                    .eq("status", 1)
                    .orderByDesc("create_time");
            return commissionRecordMapper.selectList(queryWrapper);
        } catch (Exception e) {
            log.error("获取提成记录失败: userId={}", userId, e);
            return null;
        }
    }

    @Override
    public BigDecimal getTotalCommission(String userId) {
        try {
            QueryWrapper<CommissionRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_user_id", userId)
                    .eq("status", 1)
                    .select("commission_amount");

            List<CommissionRecord> records = commissionRecordMapper.selectList(queryWrapper);
            BigDecimal total = BigDecimal.ZERO;

            for (CommissionRecord record : records) {
                total = total.add(record.getCommissionAmount());
            }

            return total;
        } catch (Exception e) {
            log.error("获取总提成金额失败: userId={}", userId, e);
            return BigDecimal.ZERO;
        }
    }

    @Override
    public BigDecimal getCommissionRatio(String userType, String memberType) {
        String key = userType + "_" + memberType;
        BigDecimal ratio = COMMISSION_RATIOS.get(key);
        if (ratio == null) {
            // 默认提成比例
            ratio = new BigDecimal("0.05");
        }
        return ratio;
    }

    @Override
    public boolean setCommissionRatio(String userType, String memberType, BigDecimal ratio) {
        try {
            String key = userType + "_" + memberType;
            COMMISSION_RATIOS.put(key, ratio);
            return true;
        } catch (Exception e) {
            log.error("设置提成比例失败: userType={}, memberType={}, ratio={}", userType, memberType, ratio, e);
            return false;
        }
    }

    /**
     * 根据用户信息确定用户类型
     */
    private String getUserType(User user) {
        if (user.getRoleId() == null) {
            return "普通用户";
        }

        switch (user.getRoleId()) {
            case 1:
                return "普通用户";
            case 2:
                return "红娘";
            case 3:
                return "会员";
            default:
                return "普通用户";
        }
    }
}
